import Panel from './panel.vue'
import CmlModule from './components/cml-module.vue'
import CmlModuleItem from './components/cml-module-item.vue'
import module from './store/index.js'
import cmlGlobal from './util/cmlGlobal'

function install(Vue, store, config = {}) {
  if (typeof store !== 'object') {
    console.warn(
      'Install failed! cmlpanel plugin depend on Vuex, you have to pass in the store instance'
    )
    return
  }
  // 注册全局变量
  Vue.prototype.$cmlG = Object.assign(cmlGlobal, {
    name: Panel.name,
    version: Panel.version
  })
  // 注册store 模块
  let { moduleName } = config
  // 默认模块
  let modules = ['cmlpanel']

  if (typeof moduleName === 'string') {
    modules.push(moduleName)
  } else if (Array.isArray(moduleName)) {
    modules = modules.concat(moduleName)
  }
  // 注册模块
  for (let i = 0; i < modules.length; i++) {
    /* if (store.state.hasOwnProperty(modules[i]) === true) {
      console.error(`cmlpanel: Vuex module ${modules[i]} has already registered. Please check the module`)
      continue
    } */
    if (i === 0) {
      // 面板默认的state
      store.registerModule('cmlpanel', module, {
        preserveState: false
      })
    } else {
      // 用户注册的state
      store.registerModule(
        modules[i],
        {
          namespaced: true,
          state: {}
        },
        {
          preserveState: false
        }
      )
    }

    // check if the plugin was correctly initialized
    if (store.state.hasOwnProperty(modules[i]) === false) {
      console.error(
        'cmlpanel: Vuex module is not correctly initialized. Please check the module name:',
        modules[i]
      )
      return
    }
  }
  // 注册组件
  Vue.component(Panel.name, Panel)
  // auto render components
  Vue.mixin({
    computed: {
      $_auth() {
        const registedComps = this.$options.components,
          name = this.$options.name
        let auth = this.$options.auth
        if (Array.isArray(auth)) {
          auth = [...auth[0].split(', ')]
        }

        let itemComp = []
        for (let comp in registedComps) {
          const rc = registedComps[comp]
          if (
            typeof rc === 'object' &&
            rc.components &&
            rc.components.CmlModuleItem
          ) {
            itemComp.push(comp.replace(comp[0], comp[0].toLowerCase()))
          }
        }

        if (!itemComp.length) {
          for (let comp in registedComps) {
            const rc = registedComps[comp]
            if (typeof rc === 'object' && rc.name === 'CmlModuleItem') {
              itemComp.push(name.replace(name[0], name[0].toLowerCase()))
            }
          }
        }
        if (auth) {
          itemComp = auth
        }
        // license
        let license = this.$store.state.cmlpanel.license,
          licenseLowerCase = license.map((l) => {
            return l.toLowerCase()
          })

        return itemComp.filter((comp) => {
          return licenseLowerCase.includes(comp.toLowerCase())
        })
      }
    }
  })
}

// 通过script标签引入
if (typeof window !== 'undefined' && window.Vue && window.store) {
  // window.cmlConfig 是可选的参数
  install(window.Vue, window.store, window.cmlConfig)
}

export default {
  install
}
// 暴露公共组件，便于二次开发
export { CmlModule, CmlModuleItem }

/**
 * @wuyax 待提供panel UI控制功能，无需抽到anvo server层！！
 * //app.init 调用
 * //通过配置初始化 各项显示、禁用、选择、展开状态
 * cmlpanel.init(config)
 *
 * cmlpanel.open()
 * cmlpanel.close()
 * cmlpanel.selectTab() -> tab.selected
 * cmlpanel.blockSingleExpand = bool 是否同时只展开一个
 * ...
 * -- 分类tab
 * tab=cmlpanel.getTabs()[0]
 * tab.visible = bool
 * tab.selected = bool
 * ...
 * -- 面板
 * blocks = tab.getBlocks()
 * block.visible = bool 是否显示
 * block.expand = bool 是否展开
 * ...
 * -- 功能服务
 * modules =  block.getModules()
 * module.enable = bool 是否禁用
 * module.visible = bool 是否显示
 * ...
 */
